package com.cfec.educationplatform.util;

import com.cfec.educationplatform.domain.Chat;
import okhttp3.*;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class OkHttpExampleUtil {
    /**
     * GetKIMI
     * @param url kimiAI的请求地址
     * @return 请求结果
     */
    public ResultData<Object> GetHomeworkDetail(String url) throws JSONException {
//        OkHttpClient client = new OkHttpClient();
        OkHttpClient client = new OkHttpClient.Builder()
                // 设置连接超时时间为10秒
                .connectTimeout(10, TimeUnit.SECONDS)
                // 设置读取超时时间为30秒
                .readTimeout(30, TimeUnit.SECONDS)
                // 设置写入超时时间为15秒
                .writeTimeout(15, TimeUnit.SECONDS)
                // 构建OkHttpClient对象
                .build();

        // 要发送的 JSON 数据
        JSONObject json = new JSONObject();
        json.put("url", url);

        // 构造 JSON 请求体
        RequestBody body = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url("http://192.168.37.232:5001/item") // 修改为你的 IP+端口
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
//                System.out.println("Response: " + response.body().string());
                String responseBody = response.body().string();
                JSONObject reponseJSON = new JSONObject(responseBody);
                String result = reponseJSON.getString("result");
                return new ResultData<>(200, "GetKIMI请求成功", result);
            } else {
                System.out.println("Request failed: " + response.code());
                System.out.println("Response: " + response.body().string());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return new ResultData<>(500, "GetKIMI请求失败", null);
    }


    /**
     * 调用kimiAi接口获取随机生成的练习题
     * @param requestBody 练习设置
     * @return 请求结果
     */
    public ResultData<Object> GetAIPractice(Map<String, String> requestBody) throws JSONException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

        // 要发送的 JSON 数据
        JSONObject json = new JSONObject();
        json.put("练习设置", requestBody);

        // 构造 JSON 请求体
        RequestBody body = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url("http://192.168.37.97:5001/item") // 修改为你的 IP+端口
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
//                System.out.println("Response: " + response.body().string());
                String responseBody = response.body().string();
                JSONObject reponseJSON = new JSONObject(responseBody);
                String result = reponseJSON.getString("result");
                return new ResultData<>(200, "题目获取成功", result);
            } else {
                System.out.println("Request failed: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return new ResultData<>(500, "GetKIMI请求失败", null);
    }

    /**
     * 调用kimiAi接口获取聊天信息
     * @param chat 用户上传的问题
     * @return 请求结果
     * @throws JSONException 异常
     */
    public ResultData<Object> Chat(Chat chat) throws JSONException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(300, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

        JSONObject json = new JSONObject();
        json.put("role", chat.getRole());
        json.put("content", chat.getContent());
        System.out.println(json.toString());
        RequestBody body = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );
        Request request = new Request.Builder()
                .url("http://127.0.0.1:5000/chat") // 修改为你的 IP+端口
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                JSONObject reponseJSON = new JSONObject(responseBody);
                String result = reponseJSON.getString("conversation_history");
                return new ResultData<>(200, "聊天成功", result);
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
        return new ResultData<>(500, "聊天失败", null);
    }
}